<?php
/**
 * com_bib      Developed using Nooku Framework 0.7 (see README.php for revision number)
 * @package		Bib
 * @copyright   Copyright (C) 2009 Danny Buytaert. All rights reserved.
 * @license     http://www.gnu.org/copyleft/gpl.html GNU/GPLv2
 */

class ComBibModelBooks extends KModelTable
{	

	public function __construct(array $options = array())
	{
		parent::__construct($options);
		
		// Set the state
		$this->_state
		 	->insert('bib_genre_id'   , 'int')
		 	->insert('bib_author_id'  , 'int')
		 	->insert('search'         , 'string')
		 	->insert('firstletter'    , 'word');
		 	//->insert('enabled'   			, 'boolean', false);
	}
	
	protected function _buildQueryJoins(KDatabaseQuery $query)
	{
		$query->join('LEFT', 'bib_authors AS au', 'au.bib_author_id = tbl.bib_author_id')
			  ->join('LEFT', 'bib_genres AS ge', 'ge.bib_genre_id = tbl.bib_genre_id');
	}
	
	protected function _buildQueryFields(KDatabaseQuery $query)
	{
		$query->select('au.name AS author')
			  ->select('ge.name AS genre');
			 
			
	}
	
	protected function _buildQueryWhere(KDatabaseQuery $query)
	{
		$state = $this->_state;
	
		if($state->bib_genre_id) {
         	$query->where('tbl.bib_genre_id', '=', $state->bib_genre_id);
       	}
       	
		if( $state->bib_author_id) {
         	$query->where('tbl.bib_author_id', '=', $state->bib_author_id);
       	}
       	
		if($state->firstletter) {
         	$query->where('tbl.title', 'Like',  $state->firstletter.'%');
       	}
       	
       	if($state->search)
		{
			$query
				  ->where('title', 'LIKE',  '%'.$state->search.'%', 'and')
				  ->where('au.name', 'LIKE',  '%'.$state->search.'%', 'or')
				  ->where('ge.name', 'LIKE',  '%'.$state->search.'%', 'or');
		}

		return $this;
	
	}
	
}